package mashibing.class8;

/**
 * 前缀树
 */
public class Class8_1_TrieTree {

    public static class Node1 {
        public int pass;
        public int end;
        public Node1[] nexts;

        public Node1() {
            pass = 0;
            end = 0;
            // 0    a
            // 1    b
            // 2    c
            // ..   ..
            // 25   z
            // nexts[i] == null   i方向的路不存在
            // nexts[i] != null   i方向的路存在
            nexts = new Node1[26];
        }
    }

    public static class Trie1{
        public Node1 root;

        public Trie1() {
            root = new Node1();
        }

        public void insert(String word) {
            if(word == null || word.length() == 0){
                return;
            }
            root.pass++;
            char[] chars = word.toCharArray();
            int index;
            Node1 next = root;
            for (int i = 0; i < chars.length; i++) {
                index = chars[i] - 'a';
                if(next.nexts[index] == null){
                    next.nexts[index] = new Node1();
                }
                next = next.nexts[index];
                next.pass++;
            }
            next.end++;
        }

        public void delete(String word) {
            if(search(word) == 0){
                return;
            }
            root.pass--;
            Node1 next = root;
            char[] chars = word.toCharArray();
            int index;
            for (int i = 0; i < chars.length; i++) {
                index = chars[i] - 'a';
                if(--next.nexts[index].pass == 0){
                    next.nexts[index] = null;
                    return;
                }
                next = next.nexts[index];
            }
            next.end--;
        }

        // word这个单词之前加入过几次
        public int search(String word) {
            if(word == null || word.length() == 0){
                return 0;
            }
            Node1 next = root;
            char[] chars = word.toCharArray();
            int index;
            for (int i = 0; i < chars.length; i++) {
                index = chars[i] - 'a';
                next = next.nexts[index];
                if(next == null){
                    return 0;
                }
            }
            return next.end;
        }

        // 所有加入的字符串中，有几个是以pre这个字符串作为前缀的
        public int prefixNumber(String pre) {
            if(pre == null || pre.length() == 0){
                return 0;
            }
            Node1 next = root;
            char[] chars = pre.toCharArray();
            int index;
            for (int i = 0; i < chars.length; i++) {
                index = chars[i] - 'a';
                next = next.nexts[index];
                if(next == null){
                    return 0;
                }
            }
            return next.pass;
        }
    }
}
